package top.lyc829.zzl_android.ui.profile.user_dtc.dynamic;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.jeremyliao.liveeventbus.LiveEventBus;

import org.jetbrains.annotations.NotNull;

import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.FragmentUserDynamicBinding;
import top.lyc829.zzl_android.logic.bean.BaseBean;
import top.lyc829.zzl_android.logic.bean.DynamicBean;
import top.lyc829.zzl_android.logic.util.DynamicType;
import top.lyc829.zzl_android.logic.util.PageInfo;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.ui.base_detail.BaseDetailActivity;
import top.lyc829.zzl_android.ui.index.RecyclerViewAdapter;
import top.lyc829.zzl_android.ui.thing.dynamic.DynamicRecyclerViewAdapter1;
import top.lyc829.zzl_android.ui.thing.dynamic_detail.DynamicDetailActivity;
import top.lyc829.zzl_android.ui.thing.travel_detail.TravelDetailActivity;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link UserDynamicFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class UserDynamicFragment extends Fragment {

    private UserDynamicViewModel mviewModel;

    UserDynamicAdapter adapter;
    FragmentUserDynamicBinding binding;

    PageInfo pageInfo = new PageInfo();

    private int otherUserId = -1;


    // TODO: Rename and change types and number of parameters
    public static UserDynamicFragment newInstance() {
        return  new UserDynamicFragment();
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = FragmentUserDynamicBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mviewModel=new ViewModelProvider(this).get(UserDynamicViewModel.class);


        LiveEventBus
                .get("logout", Integer.class)
                .observeSticky(this, new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        if (integer.equals(1)) {
                            //Utils.Sout("接收到注销消息");
                            pageInfo.reset();
                            mviewModel.getUserDynamicLiveData().setValue(null);

                        }
                    }
                });


        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        staggeredGridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);

        binding.userDynamicRecyclerview.setLayoutManager(staggeredGridLayoutManager);
        adapter=new UserDynamicAdapter();

        adapter.setAnimationEnable(true);   // recyclerview加载动画
        binding.userDynamicRecyclerview.setAdapter(adapter);

        binding.userDynamicRecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NotNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                staggeredGridLayoutManager.invalidateSpanAssignments();//这行主要解决了当加载更多数据时，底部需要重绘，否则布局可能衔接不上。
            }
        });

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Intent intent=new Intent(getActivity(),  DynamicDetailActivity.class);
                intent.putExtra("id", ((DynamicBean)adapter.getData().get(position)).getDynamicId());
                startActivity(intent);
            }
        });

        adapter.addChildClickViewIds(R.id.edit_share);
        adapter.setOnItemChildClickListener((adapter1, view, position) -> {
            if (view.getId() == R.id.edit_share) {
                goOriginDynamic(position);
            }
        });


        //request();
        binding.swipeLayout.setRefreshing(true);
        //refresh();
        initLoadMore();
        initRefreshLayout();
        observe();

    }
    // 去原始动态
    private void goOriginDynamic(int position) {
        DynamicBean item = adapter.getItem(position);
        Intent intent = null;
        if (item.getType().equals(DynamicType.BASE)) {
            intent  = new Intent(getActivity(), BaseDetailActivity.class);
            intent.putExtra("id", item.getTypeId());
        } else if (item.getType().equals(DynamicType.DYNAMIC)) {
            intent  = new Intent(getActivity(), DynamicDetailActivity.class);
            intent.putExtra("id", item.getTypeId());
        }else if (item.getType().equals(DynamicType.TRAVEL)) {
            intent  = new Intent(getActivity(), TravelDetailActivity.class);
            intent.putExtra("travel_id", item.getTypeId());
        }
        if (intent != null) {
            startActivity(intent);
        }
    }

    private void initLoadMore() {
        adapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                request();
            }
        });
        adapter.getLoadMoreModule().setAutoLoadMore(true);
        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        adapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
    }
    private void initRefreshLayout() {
        binding.swipeLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
        binding.swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
    }
    /**
     * 刷新
     */
    private void refresh() {
        // 这里的作用是防止下拉刷新的时候还可以上拉加载
        adapter.getLoadMoreModule().setEnableLoadMore(false);
        // 下拉刷新，需要重置页数
        pageInfo.reset();
        request();
    }


    //这里的user_id要怎么传过来的
    private void request() {
        if (otherUserId == -1) {
            mviewModel.getUserDynamicList(Utils.getUserId(), pageInfo.getPage());
        } else {
            mviewModel.getUserDynamicList(otherUserId, pageInfo.getPage());
        }

    }



    private void observe(){
        mviewModel.getUserDynamicLiveData().observe(getViewLifecycleOwner(), DynamicBean->
        {
            binding.swipeLayout.setRefreshing(false);
            //adapter.setList(DynamicBean);
            adapter.getLoadMoreModule().setEnableLoadMore(true);
            if(pageInfo.isFirstPage()){
                adapter.setList(DynamicBean);
            }
            else {
                adapter.addData(DynamicBean);
            }

            if (DynamicBean == null || DynamicBean.size() < PageInfo.MAX_ITEM) {
                adapter.getLoadMoreModule().loadMoreEnd();
            } else {
                pageInfo.nextPage();
                // 加载完成，等待下一次加载
                adapter.getLoadMoreModule().loadMoreComplete();
            }
        });
    }

    @Override
    public void onResume() {
        if (!Utils.isLogin()) {
            mviewModel.getUserDynamicLiveData().setValue(null);
        } else {
            request();
        }
        super.onResume();
    }

    public void setOtherUserId(int otherUserId) {
        this.otherUserId = otherUserId;
    }
}